<template>
  <div>
    <!-- 面包屑导航 -->
    <Breadcrumb :breadcrumbInfo="breadcrumbInfo"></Breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 信息提示区 -->
      <el-alert
        title="添加商品信息"
        type="info"
        :closable="false"
        center
        show-icon
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :active="activeIndex - 0"
        finish-status="success"
        align-center=""
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>

            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 选择商品分类级联选择框 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cascaderInfo.props"
                @change="handleCascaderChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!--渲染表单的Item项-->
            <el-form-item
              v-for="item in manyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <!-- 复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  v-for="(cb, i) in item.attr_vals"
                  :key="i"
                  :label="cb"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyTableData"
              :key="item.attr_id"
              :label="item.attr_name"
              ><el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="actionURl"
              :headers="headerURl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑区 -->
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" class="addbtn" @click="addGoodsintroduce"
              >添加内容</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 dialog-->
    <el-dialog
      title="图片预览"
      :visible.sync="previewDiaologInfo.isShow"
      width="50%"
    >
      <el-image class="img-sty" :src="previewDiaologInfo.imageURL"> </el-image>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from "../../components/Breadcrumb.vue";
// 富文本组件
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
// lodash深拷贝
import _ from "lodash";
export default {
  name: "Addpage",
  components: { Breadcrumb, quillEditor },
  data() {
    return {
      // 商品列表面包屑导航信息
      breadcrumbInfo: {
        titlePath: [
          { title: "首页", Path: "/Home" },
          { title: "商品管理", Path: "" },
          { title: "添加商品", Path: "" },
        ],
      },

      //   步骤条别激活的位置
      activeIndex: "0",

      //   添加商品信息对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        //商品所属的分类数组
        goods_cat: [],
        // 图片存放路径
        pics: [],
        attrs: [],
      },
      //   商品分类列表
      cateList: [],
      //   商品分类级联选择框信息
      cascaderInfo: {
        props: {
          value: "cat_id",
          label: "cat_name",
          children: "children",
        },
      },

      // 验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类信息", trigger: "blur" },
        ],
      },
      //   动态参数数据
      manyTableData: [],
      //   静态参数数据
      onlyTableData: [],

      // 图片上传URl
      actionURl: "http://127.0.0.1:8888/api/private/v1/upload",
      // 图片上传请求头
      headerURl: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 预览图片地址
      previewPath: "",
      previewDiaologInfo: {
        isShow: false,
        imageURL: "",
      },
    };
  },
  methods: {
    //   监听选择框的改变时会触发
    handleCascaderChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
        return this.$message.error("请选择三级分类!!!");
      }
    },
    //   监听标签页将要改变时会触发
    beforeTabLeave(_, oldActiveName) {
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类!!!");
        return false;
      }
    },
    //获取所有商品分类信息
    async getCateList() {
      const { data: res } = await this.$http.get("categories");

      if (res.meta.status !== 200) {
        return this.message.error("获取商品分类数据失败!");
      }

      //   保存商品数组列表
      this.cateList = res.data;
    },

    // 标签页被点击时触发
    async tabClicked() {
      //激活activeIndex 为1的页
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "many" } }
        );
        if (res.meta.status !== 200) {
          return this.message.error("获取参数列表数据失败!");
        }
        // 把字符串转化为数组,防止渲染时为空 ''
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTableData = res.data;
      } else if (this.activeIndex === "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: "only" } }
        );
        if (res.meta.status !== 200) {
          return this.message.error("获取参数列表数据失败!");
        }
        this.onlyTableData = res.data;
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewDiaologInfo.imageURL = file.response.data.url;
      this.previewDiaologInfo.isShow = true;
    },
    // 处理图片移除操作
    handleRemove(file) {
      // 1，获取将要删除的图片的临时路径
      const picsPath = file.response.data.tmp_path;
      // 2．从 pics数组中，过滤掉找到这个图片
      this.addForm.pics = this.addForm.pics.filter((i) => i.pic !== picsPath);
    },
    // 文件上传成功时的钩子
    uploadSuccess(response) {
      // 1．拼接得到一个图片信息对象
      const picinfo = { pic: response.data.tmp_path };
      // 2．将图片信息对象，push 到pics数组中
      this.addForm.pics.push(picinfo);
    },

    // 富文本提交
    addGoodsintroduce() {
      this.$refs["addFormRef"].validate(async (valid) => {
        if (!valid) {
          return this.$message.error("请填写必要的表单项目");
        }
        //执行添加的逻辑
        // lodash cloneDeep(boj) 深拷贝
        const form = _.cloneDeep(this.addForm);
        form.goods_cat = form.goods_cat.join(",");

        // 处理动态属性
        this.manyTableData.forEach((i) => {
          const newInfo = {
            attr_id: i.attr_id,
            attr_value: i.attr_vals.join(" "),
          };
          this.addForm.attrs.push(newInfo);
        });

        // 处理静态属性
        this.onlyTableData.forEach((i) => {
          const newInfo = {
            attr_id: i.attr_id,
            attr_value: i.attr_vals,
          };
          this.addForm.attrs.push(newInfo);
        });
        form.attrs = this.addForm.attrs;

        // 发请求保存数据
        console.log(form);
        const { data: res } = await this.$http.post("goods", form);
        if (res.meta.status !== 201) {
          this.$message.error("添加商品失败!");
        }
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    },
  },

  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }
      return null;
    },
  },
  created() {
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.span-info {
  font-size: 14px;
  display: block;
  margin: 10px 0;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.img-sty {
  width: 100%;
  height: 500px;
}
.addbtn {
  margin: 15px 0 0 0;
}
</style>